import React, { useState, useEffect } from 'react';
import { View } from '@tarojs/components'
import './index.scss'
const CountdownLottery = (props) => {
  const { time, fn } = props
  const getSeconds = (s) => {
    let second = parseInt(s); // 秒
    let minute = 0;
    let house = 0;
    let date = 0;
    if (second > 60) {
      //如果秒数大于60，将秒数转换成整数
      //获取分钟，除以60取整数，得到整数分钟
      minute = parseInt(second / 60);
      //获取秒数，秒数取佘，得到整数秒数
      second = parseInt(second % 60);
      //秒数
      if (minute > 60) {
        //获取小时，获取分钟除以60，得到整数小时
        house = parseInt(minute / 60);
        //获取小时后取佘的分，获取分钟除以60取佘的分
        minute = parseInt(minute % 60);
      }
      if (house > 24) {
        //获取小时，获取分钟除以24，得到整数小时
        date = parseInt(house / 24);
        //获取小时后取佘的分，获取分钟除以60取佘的分
        house = parseInt(house % 24);
      }
    }
    if (s > 0) {
      return <View className='CountdownLottery_box'>
        还有
        <View className='CountdownLottery_live_startTimeBox'>{house || '00'}</View>
        <View className='CountdownLottery_live_startTimeSize'>:</View>
        <View className='CountdownLottery_live_startTimeBox'>{minute || '00'}</View>
        <View className='CountdownLottery_live_startTimeSize'>:</View>
        <View className='CountdownLottery_live_startTimeBox'>{second || '00'}</View>
        <View className='CountdownLottery_live_startTimeSize'>开奖</View>
      </View>;
    } else return <View className='CountdownLottery_box'> 已开奖</View>;
  };
  let times =
    parseInt(new Date().getTime() / 1000) -
    parseInt(new Date(time.replace(/-/g, '/')).getTime() / 1000);
  const [interVal, setIntervals] = useState(0);
  let i = 0;
  useEffect(() => {
    let controller = true;
    let setTime;
    setTime = setInterval(() => {
      i++;
      setIntervals(times + i >= 0 ? 0 : Math.abs(times + i));
      if (times + i >= 0 || controller === false) {
        clearInterval(setTime);
        if (times + i >= 0) {
          fn && fn();
        }
      }
    }, 1000);
    return () => {
      controller = false;
      clearInterval(setTime);
    };
  }, []);
  // 自定义渲染倒计时组件的方法
  return <>{getSeconds(interVal)}</>;
};

export default CountdownLottery;